const AUTH = 'authorize';

function checkAuth(scope, autoRedirect = true) {
	const isLogined = wx.getStorageSync(AUTH);
	return new Promise((resolve, reject) => {
		// 未登录跳转登录链接
		if (!isLogined) {
			const backUrl = scope.route;
			const query = scope.query;
			let queryArr = [];
			let queryStr = '';

			// 传递query参数
			for (let key in query) {
				queryArr.push(`${key}=${query[key]}`);
			}
			if (queryArr.length) {
				queryStr = queryArr.join('&');
			}

			if (autoRedirect) { // 未登录自动重定向到登录页
				let url = backUrl + `${queryStr ? '?' + queryStr : ''}`;
				wx.redirectTo({
					url: `/pages/login/login?backUrl=${encodeURIComponent(url)}`
				})
			}
			reject();
		}
		resolve()
	})
}

export default checkAuth